const shopcart = require('../../service/shopcart.js')
var amapFile = require('../../lib/amap-wx.js');
const utils = require('../../utils/util.js');
// load promise 
require('../../utils/wx-pro.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showToast:false,
    toastMsg:'',
    allGoodslist: [],//购物车的商品列表
    pricecount: 0,// 合计的价格
    listcount: 0,//总计的数量
    edit:false,//编辑删除相关商品
    shopId:''
  },

  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.shopId) {
      var shopId = options.shopId
      this.setData({
        shopId: shopId
      })
    } else {
      var shopId = JSON.parse(wx.getStorageSync('selectShopInfo')).id
      this.setData({
        shopId: shopId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getdata()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getdata()
  },

  // 加入购物车的时候向storage里提交数据++
  // 已选商品列表里显示{名称,价格,数量}++

  // #########获取购物车列表#########
  getdata() {
    var _this=this
    var getlistarr = []
    var params = {
      shopId: this.data.shopId
    }
    shopcart.cartlist(params).then(r => {
      if (r.code == 200) {
        if (r.response.shoppingCartList.length > 0) {
          var arrlist=[]
          for (var i =0 ; i< r.response.shoppingCartList.length;i++){
            r.response.shoppingCartList[i].checked=true
            arrlist.push(r.response.shoppingCartList[i])
          }
          _this.setData({
            allGoodslist: arrlist,
            listcount: arrlist.length
          })
          _this.computedcount()
        }
      } else {
        _this.showToastFuc(r.message)
      }
    })
  },


  // ######### CHECKED #########
  changecheck(e){//设置显示的
    var idx = e.currentTarget.dataset.index  // 标识符,第几个商品
    var allGoodslist = this.data.allGoodslist
    allGoodslist[idx].checked = !allGoodslist[idx].checked
    this.setData({
      allGoodslist: allGoodslist
    })
    if(!this.data.edit){
      this.computedcount()
    }
  },


  //######### 跳转 #########
  settlement() {
    var arrlist = [].concat(this.data.allGoodslist)
    var newarr=[]
    for (var i = 0; i < arrlist .length;i++){//将被选择的商品放入新的购物车
      if (arrlist[i].checked==true){
        newarr.push(arrlist[i])
      }
    }
    if(newarr.length==0){
      this.showToastFuc("请添加商品到购物车")
      return
    }
    wx.setStorage({//设置购物车,到订单确认页调取
      key:'ShopCartList',
      data: JSON.stringify(newarr),
      success:function(){
        wx.setStorage({//此处需要在某个时候将buytype去掉
          key: 'buytype',
          data: 1,
          success: function () {
            wx.navigateTo({
              url: '../orderConfirm/orderConfirm'
            })
          }
        })
      }
    })
  },


  // ######### 加减 #########
  changenum(e) {
    var _this = this
    var idx = e.currentTarget.dataset.index  // 标识符,第几个商品
    var maths = e.currentTarget.dataset.type // 类型,是添加还是减少
    var getlistarr = []
    getlistarr = [].concat(this.data.allGoodslist)// 获取列表
    var param={}
    if (maths == "add") {// 新增的时候直接+1
      param={
        shoppingcartId: getlistarr[idx].cartId,
        num:1
      }
    } else if (maths == "red") {
      if (getlistarr[idx].num>1){
        param = {
          shoppingcartId: getlistarr[idx].cartId,
          num: -1
        }
      }else{

      }
    }
    if (!param.shoppingcartId){
      return
    }
    shopcart.changenum(param).then(r => {
      if (r.code == 200) {
        this.getdata()
      }else{
        _this.showToastFuc(r.message)
      }
    })
  },
  // ######### 合计 #########
  // 计算的同时判断购物车是否为空,为空的话,设置隐藏购物车
  computedcount() {
    var _this = this
    var getlistarr = []
    getlistarr = [].concat(this.data.allGoodslist)
    if (getlistarr.length <= 0) {
      this.setData({
        goodcart: false
      })
    } else {
      this.setData({
        goodcart: true
      })
    }
    var pricecount = 0 //总价
    for (var i = 0; i < getlistarr.length; i++) {
      if (getlistarr[i].checked){
        pricecount += parseFloat(getlistarr[i].shoppingCartGoods.goodsPrice * getlistarr[i].num)
      }
    }
    this.setData({
      pricecount: pricecount.toFixed(2),
    })
  },

  // ######### 全选 #########
  changeall(){
    var getlistarr = []
    getlistarr = [].concat(this.data.allGoodslist)// 获取列表
    var arrlist = []
    for (var i = 0; i < getlistarr.length; i++) {
      getlistarr[i].checked = true
      arrlist.push(getlistarr[i])
    }
    this.setData({
      allGoodslist: arrlist
    })
    this.computedcount()
  },
  // ######### 编辑 #########
  edittodel(){
    this.setData({
      edit: !this.data.edit,
    })
    if(this.data.edit){
      var goodlistarr = []
      goodlistarr = this.data.allGoodslist
      for (var i = 0; i < goodlistarr.length; i++) {
        goodlistarr[i].checked = false
      }
      this.setData({
        allGoodslist: goodlistarr
      })
    }else{
      this.getdata()
    }
  },
  // ######### 删除 #########
  delitem(){
    var _this=this
    if (_this.data.allGoodslist.length == 0) {
      _this.showToastFuc('购物车无商品')
      return
    }
    wx.showModal({
      title:"提示",
      content:"确认删除选中商品?",
      cancelColor:"#46A141",
      success:function(){
        console.log("11111111")
          var goodlistarr = []
          goodlistarr = _this.data.allGoodslist
          var cartids=''
          for (var i = 0; i < goodlistarr.length; i++) {
            if (goodlistarr[i].checked == true) {
              cartids+=goodlistarr[i].cartId+','
            }
          }
          var param = {
            cartId: cartids
          }
          console.log(param)
          shopcart.delcart(param).then(r=>{
            console.log(r)
            if(r.code==200){
              _this.setData({
                edit: false
              })
              _this.getdata()
            }else{
              _this.showToastFuc('删除失败,请检查网络')
            }
          })
      }
    })
    
  }


})